﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using dotNetDR_OAuth2;
using dotNetDR_OAuth2.AccessToken;
using dotNetDR_OAuth2.APIs;
using OnlineMealOrdering.Common;
using OnlineMealOrdering.Extends.Attributes;
using OnlineMealOrdering.Models;
using OnlineMealOrdering.Persistence;

namespace OnlineMealOrdering.Controllers
{
    public class OAuth2Controller : Controller
    {
        private IAuthorizationCodeBase sina = UnityFactory.Create(CtorAT.Sina);
        private IAuthorizationCodeBase tencent = UnityFactory.Create(CtorAT.Tencent);

        private IAuthorizationCodeBase _authCodeTencent = UnityFactory.Create(CtorAT.Tencent);
        private TencentError _tencentErr = null;
        private IApi tencentApi = UnityFactory.Create(CtorApi.Tencent);


        private IAuthorizationCodeBase _authCodeSina = UnityFactory.Create(CtorAT.Sina);
        private TencentError _sinaErr = null;
        private IApi sinaApi = UnityFactory.Create(CtorApi.Sina);

        public ActionResult PartialOAuth2LoginPane()
        {
            dynamic model = new ExpandoObject();

            var hostPath = AccessTokenToolkit.GenerateHostPath(Request.Url);//生成主机头例如：http://www.yourhost.com:8081 (注：默认80端口则不会显示:80)
            var sinaRedirectUrl = hostPath + Url.Action("Sina", "OAuth2");//定义授权成功后返回的url地址
            var tencentRedirectUrl = hostPath + Url.Action("Tencent", "OAuth2");

            model.SinaLink = sina.GenerateCodeUrl(sinaRedirectUrl);
            model.TencentLink = tencent.GenerateCodeUrl(tencentRedirectUrl);
            Session.Remove("accessToken");
            return View(model);
        }

        public ActionResult Sina(string code)
        {
            using (var ctx = new OnlineStoreDomainContext())
            {
            }
            if (!string.IsNullOrEmpty(code))
            {
                var redirectUrl = AccessTokenToolkit.GenerateHostPath(Request.Url) + Url.Action("Sina");

                var accessToken = _authCodeSina.GetResult(_authCodeSina.GenerateAccessTokenUrl(redirectUrl, code));
                if (!string.IsNullOrWhiteSpace(code))
                {
                    if (Session["accessToken"] != null)
                    {

                    }
                }

                //if (tencentApi.WasError(accessToken, out _tencentErr))
                //{
                //    Session["err"] = _sinaErr;
                //    return RedirectToAction("Error");
                //}

                //Session.Add("accessToken", accessToken);

                return View(new object());
            }
            return RedirectToAction("Index", "Home");
        }


        public ActionResult Tencent(string code, string openid, string openkey)
        {
            using (var ctx = new OnlineStoreDomainContext())
            {
                if (Session["accessToken"] != null)
                    return View(new object());
                if (!string.IsNullOrEmpty(code))
                {
                    var redirectUrl = AccessTokenToolkit.GenerateHostPath(Request.Url) + Url.Action("Tencent");
                    var accessToken = _authCodeTencent.GetResult(_authCodeTencent.GenerateAccessTokenUrl(redirectUrl, code));
                    if (tencentApi.WasError(accessToken, out _tencentErr))
                    {
                        Session["err"] = _authCodeTencent;
                        return RedirectToAction("Error");
                    }

                    accessToken.openid = openid;
                    accessToken.openkey = openkey;
                    Session.Add("accessToken", accessToken);

                    var data = ShowInfo();

                    //保存数据库 模拟登陆 跳转到完善用户页面
                    if (AccountModel.IsExistsUser(openid))
                    {
                        //如果已经存在该用户则验证 后登陆
                        if (AccountModel.OAuth2ValidateUser(openid, openkey))
                            OAuth2Login(openid, openkey);
                    }
                    else
                    {
                        //不存在就添加新用户, 登陆 在跳转到完善资料页面 
                        AccountModel.CreateOAuth2User(accessToken.name, accessToken.access_token, accessToken.expires_in, accessToken.refresh_token, accessToken.openid, accessToken.openkey, string.IsNullOrWhiteSpace(data.nick) ? data.name : (data.nick+data.name));
                        ctx.SubmitChanges();
                        OAuth2Login(openid, openkey);

                        //关注指定账户的微博

                        //发送一条微博
                        PublishMsg();
                    }





                }


                return RedirectToAction("Index", "Home");
            }
        }

        public void OAuth2Login(string openid, string openkey)
        {
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Account");
            routeData.Values.Add("action", "SimulateOAuthLogin");
            routeData.Values.Add("openid", openid);
            routeData.Values.Add("openkey", openkey);
            RequestContext requestContext = new RequestContext(new HttpContextWrapper(System.Web.HttpContext.Current), routeData);
            ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, "Account").Execute(requestContext);
        }


        //[AccessTokenRequired]
        //public ActionResult ShowUserInfo()
        //{

        //    //var accessTokenObj = Session["accessToken"] as dynamic;
        //    //var uid = accessTokenObj.uid;
        //    //var accessToken = accessTokenObj.access_token;
        //    //var model = tencentApi.CallGet("user/info?format=json", accessToken, false, GetOpenidOpenkeyParamsExt());
        //    return View(ShowInfo());
        //}

        public ActionResult TencentError()
        {
            var err = Session["err"] as TencentError;

            return View(err);
        }
        public ActionResult SinaError()
        {
            var err = Session["err"] as SinaError;

            return View(err);
        }

        [NonAction]
        private IDictionary<string, object> GetOpenidOpenkeyParamsExt()
        {
            var result = new Dictionary<string, object>();

            var accessTokenObj = Session["accessToken"] as dynamic;
            var openid = accessTokenObj.openid;
            var openkey = accessTokenObj.openkey;

            result.Add("openid", openid);
            result.Add("openkey", openkey);

            return result;
        }

        private void OAuthManage()
        {
        
        }

        dynamic ShowInfo()
        {
            var accessTokenObj = Session["accessToken"] as dynamic;
            var uid = accessTokenObj.uid;
            var accessToken = accessTokenObj.access_token;
            var model = tencentApi.CallGet("user/info?format=json", accessToken, false, GetOpenidOpenkeyParamsExt());
            return model.data;
        }

        void PublishMsg()
        {
            try
            {
                var accessTokenObj = Session["accessToken"] as dynamic;
                var accessToken = accessTokenObj.access_token;

                var msg = WeiboMsg.GetMsg();
                var formData = new Dictionary<string, string>();
                formData.Add("content", Server.UrlEncode(msg));
                //formData.Add("pic_url", "http://t3.qpic.cn/mblogpic/8dfda56a1df2366b9f18/120");
                //formData.Add("longitude", ""); 
                //formData.Add("latitude", "");

                //var url = UploadWeiBoImage("http://t3.qpic.cn/mblogpic/8dfda56a1df2366b9f18/120");
                //if (!string.IsNullOrWhiteSpace(url))
                //    formData.Add("pic_url",url);
                var result = tencentApi.CallPost("t/add?format=json", accessToken, formData, false, GetOpenidOpenkeyParamsExt());

            }
            catch (Exception ex)
            {
                //
            }
        }

        string UploadWeiBoImage(string url)
        {
            var accessTokenObj = Session["accessToken"] as dynamic;
            var accessToken = accessTokenObj.access_token;

            var formData = new Dictionary<string, string>();
            formData.Add("pic_url", url);
            var result = tencentApi.CallPost("t/upload_pic?format=json", accessToken, formData, false, GetOpenidOpenkeyParamsExt());
            if (result.data.msg == "ok")
                return result.data.imgurl;
            return "";
        }
    }
}
